`
|
Redirects output of a command as input to another command
Let’s practice using redirection operators to see how they work
with standard streams. The > operator redirects the standard output
stream to a file. Any command that precedes this character will send
its output to the specified location. Run the following command
directly in your terminal:
$ echo "Hello World!" > output.txt
We redirected the standard output stream to a file named
output.txt. To see the content of output.txt, simply run the following:
$ cat output.txt
Hello World!
Next, we’ll use the >> operator to append some content to the
end of the same file:
$ echo "Goodbye!" >> output.txt
$ cat hello_output.txt
Hello World!
Goodbye!
Listing 1-10
Append text to a file
If we used > instead of >>, the content of output.txt would have
been overwritten completely with the Goodbye! text.
You can redirect both the standard output stream and the
standard error stream to a file using &>. This is useful when you
don’t want to send any output to the screen and instead save
everything in a log file (perhaps for later analysis).
ls -l / &> stdout_and_stderr.txt
Listing 1-11
Redirecting standard output and standard error streams to a file
To append both the standard output and standard error streams to
a file, simply use double chevron (&>>).
What if we wanted to send the standard output stream to one file,
and the standard error stream to another? This is also possible using
the streams’ file descriptor numbers:
$ ls -l / 1> stdout.txt 2> stderr.txt
Listing 1-12
Redirecting standard output and standard error to separate files
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks